from flask import request, jsonify
from app.extensions import db
from app.models import Relationship, RelationshipSchema
from . import api_bp

relationship_schema = RelationshipSchema()
relationships_schema = RelationshipSchema(many=True)

@api_bp.route('/relationships', methods=['GET'])
def get_relationships():
    try:
        chart_id = request.args.get('chart_id')
        if chart_id:
            relationships = Relationship.query.filter_by(chart_id=chart_id, status='active').all()
        else:
            relationships = Relationship.query.filter_by(status='active').all()

        result = relationships_schema.dump(relationships)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/relationships/<int:relationship_id>', methods=['GET'])
def get_relationship(relationship_id):
    try:
        relationship = Relationship.query.get(relationship_id)
        if not relationship:
            return jsonify({
                'code': 404,
                'message': 'Relationship not found',
                'data': None
            }), 404

        result = relationship_schema.dump(relationship)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/relationships', methods=['POST'])
def create_relationship():
    try:
        data = request.get_json()
        relationship = Relationship(**data)
        db.session.add(relationship)
        db.session.commit()

        result = relationship_schema.dump(relationship)
        return jsonify({
            'code': 201,
            'message': 'Relationship created successfully',
            'data': result
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/relationships/<int:relationship_id>', methods=['PUT'])
def update_relationship(relationship_id):
    try:
        relationship = Relationship.query.get(relationship_id)
        if not relationship:
            return jsonify({
                'code': 404,
                'message': 'Relationship not found',
                'data': None
            }), 404

        data = request.get_json()
        for key, value in data.items():
            if hasattr(relationship, key):
                setattr(relationship, key, value)

        db.session.commit()
        result = relationship_schema.dump(relationship)
        return jsonify({
            'code': 200,
            'message': 'Relationship updated successfully',
            'data': result
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/relationships/<int:relationship_id>', methods=['DELETE'])
def delete_relationship(relationship_id):
    try:
        relationship = Relationship.query.get(relationship_id)
        if not relationship:
            return jsonify({
                'code': 404,
                'message': 'Relationship not found',
                'data': None
            }), 404

        db.session.delete(relationship)
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': 'Relationship deleted successfully',
            'data': None
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500